<template>
  <div class="quality-order full-height bg-white page-content content relative-position">
    <collapse ref="collapse" class="collapse-content after">
        <template v-slot:content>
          <yz-condition-filter
            v-model="queryParams"
            @resetSearch="resetSearch"
            @onSubmit="submit"
          >
            <select-tooltip
                    v-model="queryParams.status"
                    :multiple="false"
                    isShowAll
                    :options="statusOptions"
                    msg="质检状态"
              ></select-tooltip>
              <yz-input
                v-model.trim="queryParams.date"
                class="q-mr-md"
                inputType="date"
                isTip
                clearable
                title="制单日期"
              ></yz-input>
              <workshop-search v-model="queryParams" ref="workShopSearch" @onReady="onReady" :is-shift="false" :urlId="viewPrivilegeId"/>
            <yz-input
              v-model.trim="queryParams.productSpec"
              class="q-mr-md"
              title="产品规格"
            />
          </yz-condition-filter>
          <div class="form-inline" style="float:right">
            <select-input ref="selectInput"
                          :list="searchCondition"
                          @search="inputSearch"
                          longWidth="350px"
                          @clearSearchVal="clearSearchVal" />
          </div>
      </template>
    </collapse>
    <q-table :data="tableData"
             :columns="tableColumns"
             row-key="id"
             class="myTable scroll stick-last-col"
             :pagination.sync="pagination"
             :hide-bottom="tableData.length !== 0"
             :loading="isTableLoading"
             color="primary">
      <template v-slot:header-cell-id="props">
        <q-th :props="props"
              class="sortable"
              :class="[sortBy == 'qualityControlOrderNum' ? 'sorted' : '','sort-' +value]"
              @click="sortable('qualityControlOrderNum')">
          {{ props.col.label }}
          <q-icon name="arrow_upward"
                  size="16px"
                  class="q-table__sort-icon" />
        </q-th>
      </template>
      <template v-slot:header-cell-createDate="props">
        <q-th :props="props"
              class="sortable"
              :class="[sortBy == 'createTime' ? 'sorted' : '','sort-' +value]"
              @click="sortable('createTime')">
          {{ props.col.label }}
          <q-icon name="arrow_upward"
                  size="16px"
                  class="q-table__sort-icon" />
        </q-th>
      </template>
      <template v-slot:header-cell-status="props">
        <q-th :props="props"
              class="sortable"
              :class="[sortBy == 'status' ? 'sorted' : '','sort-' +value]"
              @click="sortable('status')">
          {{ props.col.label }}
          <q-icon name="arrow_upward"
                  size="16px"
                  class="q-table__sort-icon" />
        </q-th>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props" :class="{'line-table': props.row.__index % 2}">
          <q-td key="expand" class="expand">
            <q-btn size="sm" flat round dense @click="expandRow(props.row)" :icon="props.row.expand ? 'iconfont icontubiao-40' : 'iconfont icontubiao-43'" />
          </q-td>
          <template v-for="key in colums">
            <q-td v-if="key === 'status'" key="status" :props="props">
            <div class="state create" style="min-width: 76px"
                  v-if="props.row.status == '0'"><span></span>新建</div>
              <div class="state closed" style="min-width: 76px"
                    v-if="props.row.status == '10'"><span></span>关闭</div>
            </q-td>
            <q-td v-else-if="key==='workOrderId'" key="workOrderId" :props="props" >
              <q-btn flat
                     color="primary"
                     :label="props.row.workOrderId"
                     class="table-flat-btn"
                     @click="goProcessOrder(props.row.workOrderId, props.row.workshopId)" />
            </q-td>
            <q-td v-else-if="key === 'productStandard'" key="productStandard" :props="props">
              <td-spec :rowData="props.row"/>
            </q-td>
            <q-td v-else :key="key" :props="props">
            <span style="width: 100%"
                  class="text-ellipsis">{{props.row[key]}}</span>
            </q-td>
          </template>
          <q-td key="operate" :props="props">
            <q-btn flat
                   color="primary"
                   label="处理进程"
                   class="table-flat-btn"
                   @click="showRecordDialog(props.row.id)"/>
            <q-btn flat
                   color="primary"
                   label="关闭"
                   class="table-flat-btn"
                   @click="closeQuality(props.row)"
                   :disable="props.row.status + '' === '10' || props.row.isWorkOrderFinished === '否'" />
          </q-td>
        </q-tr>
        <q-tr v-show="props.row.expand" :props="props">
          <q-td colspan="100%" class="expand">
            <div class="text-grey flex items-center" style="padding-left:30px;height: 100%" v-if="!props.row.qualityControlSubOrders.length">暂无数据</div>
            <div class="flex items-center" v-for="(item,index) in props.row.qualityControlSubOrders" :key="index">
              <div class="flex items-center td-item">
                <div class="text-grey flex" style="width: 210px">加工班次：
                  <span class="text-black text-ellipsis" style="max-width: 120px">{{item.shiftName}}</span>
                  <q-tooltip>{{item.shiftName}}</q-tooltip>
                </div>
                <div class="text-grey" style="width: 140px">报检数量：<span class="text-black">{{item.qualityControlCount}}</span></div>
                <div class="text-grey" style="width: 140px">质检数量：<span class="text-black">{{item.qualityCount}}</span></div>
                <div class="text-grey" style="width: 140px">不良数量：<span class="text-black">{{item.defectiveCount}}</span></div>
<!--                <div class="text-grey" style="width: 140px">让步数量：<span class="text-black">{{item.compromiseCount}}</span></div>-->
              </div>
              <div>
                <q-btn flat
                       color="primary"
                       label="质检录入"
                       class="table-flat-btn"
                       :disable="props.row.status + '' === '10' || item.qualityControlCount === 0 || item.qualityControlCount === (item.defectiveCount + item.compromiseCount)"
                       v-has="{id: Enums.SYS_PERMISSION.INPUT_BAD_NUM_BTN.value}"
                       v-stat="{id:CommonConfig.statData.qualityOrder.edit.id,name:CommonConfig.statData.qualityOrder.edit.name}"
                       @click="defectiveDialog(props.row, item)" />
                <q-btn flat
                       color="primary"
                       label="不良记录"
                       class="table-flat-btn"
                       v-has="{id: Enums.SYS_PERMISSION.INPUT_BAD_NUM_BTN.value}"
                       v-stat="{id:CommonConfig.statData.qualityOrder.edit.id,name:CommonConfig.statData.qualityOrder.edit.name}"
                       @click="showBadQuantityQialog(props.row, 'partscause', item)" />
<!--                <q-btn flat-->
<!--                       color="primary"-->
<!--                       label="让步记录"-->
<!--                       class="table-flat-btn"-->
<!--                       v-has="{id: Enums.SYS_PERMISSION.INPUT_BAD_NUM_BTN.value}"-->
<!--                       v-stat="{id:CommonConfig.statData.qualityOrder.edit.id,name:CommonConfig.statData.qualityOrder.edit.name}"-->
<!--                       @click="showBadQuantityQialog(props.row, 'concession', item)" />-->
              </div>
            </div>
          </q-td>
        </q-tr>
      </template>
    </q-table>
    <yz-pagination v-model="pagination" @onSearch="getList"/>
    <add-quality-item ref="addQualityItem" @getList="getList" />
    <bad-quantity-dialog ref="badQuantityQialog" @getList="getList"/>
    <record-dialog ref="qualityLogs"/>
  </div>
</template>

<script>
import SelectInput from 'src/components/select-input/index'
import addQualityItem from './components/quality/add-quality-item'
import {
  getQualityOrders,
  closeQualityOrder
} from 'src/boot/job/quality-order'
import { getShiftDate
} from 'src/boot/job/process-order'
import { mapGetters } from 'vuex'
import refreshMixin from 'src/assets/js/refresh-mixin'
import badQuantityDialog from './components/quality/bad-quantity-dialog'
import recordDialog from './components/quality/record-dialog'
import moment from 'moment'
import Collapse from 'src/components/collapse'
import _ from 'lodash'
import { getViewPrivilegeId } from '../../assets/js/enums'

export default {
  name: 'quality-order',
  mixins: [refreshMixin],
  components: {
    SelectInput,
    addQualityItem,
    badQuantityDialog,
    recordDialog,
    Collapse
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  data () {
    return {
      viewPrivilegeId: getViewPrivilegeId('qualityOrder'),
      selId: null, // 所选行id
      colums: [], // 列
      queryParams: {
        productSpec: '',
        date: [],
        status: 'all',
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        },
        devices: ['all'],
        workshopId: ''
      }, // 查询条件对象
      statusOptions: [], // 状态源数据
      isOver: false,
      // 搜索条件
      searchCondition: [
        { id: 'qualityControlOrderNum', name: '质检单号', statId: this.CommonConfig.statData.qualityOrder.searchByQualityOrderNum.id },
        { id: 'orderNumber', name: '订单号', statId: this.CommonConfig.statData.qualityOrder.searchByOrderNum.id },
        { id: 'productName', name: '产品名称', statId: this.CommonConfig.statData.qualityOrder.searchByProductName.id },
        { id: 'productNumber', name: '产品编号' },
        { id: 'workOrderNum', name: '工单编号' }
      ],
      searchBy: '', // 搜索条件 deviceNum or deviceName
      keyword: '', // 搜索值
      // 表格头部数据
      tableColumns: [
        { name: 'expand', field: 'expand', label: '', align: 'left' },
        { name: 'id', field: 'id', label: '质检单号', align: 'left' },
        { name: 'productNumber', field: 'productNumber', label: '产品编号', align: 'left' },
        { name: 'productName', field: 'productName', label: '产品名称', align: 'left' },
        { name: 'productStandard', field: 'productStandard', label: '产品规格', align: 'left' },
        { name: 'processName', field: 'processName', label: '加工工序', align: 'left' },
        { name: 'workOrderId', field: 'workOrderId', label: '工单编号', align: 'left' },
        { name: 'status', field: 'status', label: '质检状态', align: 'left' },
        { name: 'createDateTime', field: 'createDateTime', label: '制单时间', align: 'left' },
        { name: 'deviceName', field: 'deviceName', label: '加工设备', align: 'left' },
        { name: 'isWorkOrderFinished', field: 'isWorkOrderFinished', label: '是否完工', align: 'left' },
        { name: 'finishedCount', field: 'finishedCount', label: '完工数量', align: 'left' },
        { name: 'qualityControlCount', field: 'qualityControlCount', label: '报检数量', align: 'left' },
        { name: 'qualityCount', field: 'qualityCount', label: '质检数量', align: 'left' },
        { name: 'defectiveCount', field: 'defectiveCount', label: '不良数量', align: 'left' },
        { name: 'measureUnit', field: 'measureUnit', label: '计量单位', align: 'left' },
        { name: 'personalName', field: 'personalName', label: '质检人', align: 'left' },
        { name: 'qualityControlDateTime', field: 'qualityControlDateTime', label: '质检日期', align: 'left' },
        { name: 'orderNumber', field: 'orderNumber', label: '订单号', align: 'left' },
        { name: 'orderBatch', field: 'orderBatch', label: '批次号', align: 'left' },
        { name: 'operate', field: 'operate', label: '操作', align: 'center' }
      ],
      // 表格内容
      tableData: [],
      // 表格分页配置
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      // 排序字段
      sortBy: '',
      // 排序（正序/倒序）
      value: '',
      // 表格正在加载
      isTableLoading: false,
      isInit: true,
      routeFromName: ''
    }
  },
  watch: {},
  beforeRouteEnter (to, from, next) {
    if (to.name === 'qualityOrder' && (from.name === 'equipmentRecordDetail' || from.name === 'statsMonitor')) {
      next(vm => {
        vm.routeFromName = from.name
        !_.isEmpty(to.params) ? vm.searchByOrder() : vm.getListInit()
      })
    } else {
      next(vm => {
        vm.getListInit()
      })
    }
  },
  methods: {
    getListInit () {
      this.isInit ? this.$refs.workShopSearch.getWorkshops().then(() => {
        this.routeFromName = ''
        this.getList()
      }) : this.getList()
    },
    // 从质检工单跳转过来。
    searchByOrder () {
      const { workshopId } = this.$route.params
      this.$refs.workShopSearch.initData(false, { workshopId })
    },
    // 赋值成功
    onReady () {
      // 质检工单跳转过来
      if (this.$route.params?.orderId) {
        const type = this.routeFromName === 'equipmentRecordDetail' ? 0 : 4
        this.$refs.selectInput.setVal(this.$route.params?.orderId, type)
      }
    },
    // 获取质检列表
    getList () {
      this.isInit = false
      console.log(this.isInit)
      const { location } = this.queryParams
      this.isTableLoading = true
      const params = {
        keyword: this.keyword || null,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        searchBy: this.searchBy || null,
        sortBy: this.sortBy || null,
        value: this.value || null,
        status: this.queryParams.status === 'all' ? null : this.queryParams.status,
        startDate: this.queryParams.date[0] ? moment(this.queryParams.date[0]).format('YYYY-MM-DD') : null,
        endDate: this.queryParams.date[1] ? moment(this.queryParams.date[1]).add(1, 'days').format('YYYY-MM-DD') : null
      }
      params.deviceTreeReqVO = {
        deviceIds: this.queryParams.devices[0] !== 'all' ? this.queryParams.devices : [],
        level: location.level || null,
        schemeId: location.id || null
      }
      if (_.isEmpty(params.deviceTreeReqVO.deviceIds) && _.isNil(params.deviceTreeReqVO.level) && _.isNil(params.deviceTreeReqVO.schemeId)) {
        this.$message.warning('请选择所在位置')
        this.isTableLoading = false
        return
      }
      this.queryParams.productSpec + '' !== '' && (params['productSpec'] = this.queryParams.productSpec)
      getQualityOrders(params).then(res => {
        this.tableData = res.data.list.map(i => {
          i.createDateTime = moment(i.createDate).format('YYYY-MM-DD HH:mm:ss')
          // 判断有无质检人
          if (i.qualityControlPersonalName) {
            i.personalName = i.qualityControlPersonalName
          } else {
            i.personalName = ''
          }
          i.qualityControlDateTime = i.qualityControlDate ? moment(i.qualityControlDate).format('YYYY-MM-DD HH:mm:ss') : ''
          i.isWorkOrderFinished = i.isWorkOrderFinished ? '是' : '否'
          _.map(this.tableColumns, 'field').map(k => {
            i[k] = this.$utils.label(i[k])
          })
          i.btnDisable = false
          i.expand = this.selId === i.id
          i.processName = `${Number(i.sort) + 1}-${i.processName}`
          return i
        })
        const expandItem = this.tableData.find(i => i.expand)
        this.selId = expandItem === undefined ? null : expandItem.id // 重置
        this.tableData = res.data.list
        this.pagination.rowsNumber = res.data.total
      }).finally(() => {
        this.isTableLoading = false
      })
    },
    // 不良录入弹出框
    defectiveDialog (data, item) {
      this.$refs.addQualityItem.showDialog(data, item)
    },
    // 修改所选区间
    changeSelRange () {
      let isOver = false
      isOver = Math.abs(moment(this.queryParams.date[0]).diff(moment(this.queryParams.date[1]), 'days')) > 60
      // tips = '(日视图下,日期范围最大不可超过60天)'
      if (isOver) {
        this.isOver = true
        this.$message.warning('所选日期范围已超出60天')
      } else {
        this.isOver = false
      }
    },
    /**
     * 重置查询条件
     */
    resetSearch () {
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      this.$refs.workShopSearch.initData()
    },
    // 搜索
    inputSearch (item, searchVal) {
      this.searchBy = item.id
      this.keyword = searchVal
      this.pagination.pageNum = 1
      this.getList()
    },
    // 清空搜索
    clearSearchVal () {
      this.searchBy = ''
      this.keyword = ''
      this.getList()
    },
    // 表格排序
    sortable (type) {
      this.tableData = []
      if (this.sortBy === type) {
        if (this.value) {
          this.value = this.value === 'asc' ? 'desc' : 'asc'
        } else {
          this.value = 'asc'
        }
      } else {
        this.sortBy = type
        this.value = 'asc'
      }
      this.pagination.pageNum = 1
      this.getList()
    },
    // 查询按钮
    submit () {
      this.pagination.pageNum = 1
      this.getList()
    },
    // 关闭质检单
    closeQuality (item) {
      this.$utils.showMessage('icontubiao-28', '确认关闭所选质检单？', () => {
        const params = {
          id: item.id
        }
        closeQualityOrder(params).then(res => {
          if (res.code === '1200') {
            this.$message.success('质检单关闭成功')
            this.getList()
          }
        })
      }, true)
    },
    // 收起展开
    expandRow (data) {
      const isTrue = this.tableData.filter(item => item.expand)[0]
      if (isTrue && isTrue.__index === data.__index) {
        this.tableData[data.__index].expand = false
        this.selId = null
      } else {
        isTrue && (this.tableData[isTrue.__index].expand = false)
        this.tableData[data.__index].expand = true

        this.selId = data.id
      }
    },
    // 不良/ 让步记录
    showBadQuantityQialog (data, type, item) {
      this.$refs.badQuantityQialog.showDialog(data, type, item)
    },
    // 处理进程
    showRecordDialog (id) {
      this.$refs.qualityLogs.showDialog(id)
    },
    // 获取当前车间的班次日期
    getShiftDate () {
      const workshopId = this.queryParams.workshopId
      return new Promise(resolve => {
        if (workshopId) {
          getShiftDate(workshopId).then(res => {
            if (res.data && /^\d{4}(-)(1[0-2]|0?\d)\1([0-2]\d|\d|30|31)$/.test(res.data)) {
              this.queryParams.date = [new Date(res.data), new Date(res.data)]
            } else {
              this.queryParams.date = []
            }
            resolve()
          })
        } else {
          resolve()
        }
      })
    },
    // 跳转到加工工单页面
    goProcessOrder (orderId, workshopId) {
      const params = {
        orderId,
        workshopId
      }
      this.$router.push({
        name: 'processOrder',
        params
      })
    }
  },
  mounted () {
    this.visibleColumns = _.map(this.tableColumns, 'field')
    this.colums = _.cloneDeep(this.visibleColumns).slice(1, this.visibleColumns.length - 1)
    this.statusOptions = this.$getEnum(this.Enums.BUSINESS_STATUS).filter(entry => entry.quality)
  }
}
</script>

<style scoped lang="stylus">
.link {
  cursor: pointer
  color $primary
}
.quality-order
  >>>.q-select{
    align-items center !important
  }
  >>> .myTable {
    tbody tr{
      td {
        background-color #fff !important
      }
      &:hover td {
        background-color: #e8ebff !important
      }
    }

    tbody .line-table {
      td {
        background-color #f9f9f9 !important
      }
    }
    .last {
      position sticky
      right 30px
    }
    .expand{
      padding-left 10px !important
      padding-right 0px !important
      width 40px !important
    }
    tbody .expand>div{
      border-bottom: 1px solid #d3d3d3
      &:first-child{
        border-top 1px solid #d3d3d3
      }
    }
  }
  .form-inline.bottom .right.box
    flex-wrap nowrap
  .form-inline .box
    display flex
    flex-wrap wrap
    justify-content flex-start
    align-items center
  .state>span
    display inline-block
    width 10px
    height 10px
    border-radius 50%
    margin-right 5px
  .state.create>span
    background-color $primary
  .state.closed>span
    background-color #999

</style>
